package com.android.xueshengzhouzhi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.android.db.DBHelpter;
import com.android.model.Messageg;
import com.android.until.RefreshableView;
import com.android.until.RefreshableView.PullToRefreshListener;
import com.android.until.Until;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.umeng.analytics.MobclickAgent;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class InfoListAct extends Activity {
	// UI控件
	private static ListView list;
	private static List<Messageg> messagegs;
	private static SimpleAdapter adapter;
	private static DBHelpter help;
	private static Map<String, String> map;
	private static List<Map<String, String>> maplist;
	private ProgressDialog dlog;
	private static RefreshableView refreshableView;
	private static ProgressBar progressBar;
	private static Button bt_load_more;
	public static int FLAG = 1;
	private static View moreView;
	private int lastVisibleIndex;
	private int totalItemCounts;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0: {

				System.out.println("the flag is " + FLAG);

				messagegs = help.findlist(FLAG);

				for (int i = messagegs.size() - 1; i >= 0; i--) {
					map = new HashMap<String, String>();
					map.put("title", messagegs.get(i).GetTitle());
					map.put("from", messagegs.get(i).GetFrom());
					map.put("time", messagegs.get(i).GetTime());
					map.put("url", messagegs.get(i).GetUrl());
					maplist.add(map);
				}

				adapter = new SimpleAdapter(InfoListAct.this, maplist,
						R.layout.listadapter, new String[] { "title", "from",
								"time", "url" }, new int[] { R.id.tv_title,
								R.id.tv_from, R.id.tv_time });

				list.addFooterView(moreView);

				list.setAdapter(adapter);

				System.out.println("has receiver message");
				// 关闭ProgressDialog
				dlog.dismiss();
				// 更新UI
				System.out.println("dlg has been stoped");

				break;
			}
			case 2:

			{
				messagegs = help.findlist(FLAG);

				for (int i = messagegs.size() - 1; i >= 0; i--) {
					map = new HashMap<String, String>();
					map.put("title", messagegs.get(i).GetTitle());
					map.put("from", messagegs.get(i).GetFrom());
					map.put("time", messagegs.get(i).GetTime());
					map.put("url", messagegs.get(i).GetUrl());
					maplist.add(map);
				}

				adapter = new SimpleAdapter(InfoListAct.this, maplist,
						R.layout.listadapter, new String[] { "title", "from",
								"time", "url" }, new int[] { R.id.tv_title,
								R.id.tv_from, R.id.tv_time });
				// 一定要放到setAdapter之前
				list.addFooterView(moreView);

				list.setAdapter(adapter);

				System.out.println("has receiver message");

				refreshableView.finishRefreshing();

				break;
			}
			case 3: {

				adapter = new SimpleAdapter(InfoListAct.this, maplist,
						R.layout.listadapter, new String[] { "title", "from",
								"time", "url" }, new int[] { R.id.tv_title,
								R.id.tv_from, R.id.tv_time });
				// 一定要放到setAdapter之前
				list.addFooterView(moreView);

				list.setAdapter(adapter);
				list.setSelection(FLAG * 12);
				progressBar.setVisibility(View.GONE);
				bt_load_more.setVisibility(View.VISIBLE);

			}

			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// ///////启动sdk
		XGPushConfig.enableDebug(this, true);
		XGPushManager.registerPush(getApplicationContext());
		// ///////

		// UI初始化
		setContentView(R.layout.activity_info_list);

		moreView = getLayoutInflater().inflate(R.layout.load_more, null);
		bt_load_more = (Button) moreView.findViewById(R.id.bt_load);
		progressBar = (ProgressBar) moreView.findViewById(R.id.pro_more);

		list = (ListView) findViewById(R.id.list);
		help = new DBHelpter(InfoListAct.this);
		maplist = new ArrayList<Map<String, String>>();
		messagegs = new ArrayList<Messageg>();
		messagegs = help.findlist(FLAG);
		refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);

		// System.out.println("the message is " + messagegs.toString());
		list.addFooterView(moreView);
		if (messagegs != null) {
			System.out.println("message has get from db");

			for (int i = messagegs.size() - 1; i >= 0; i--) {
				map = new HashMap<String, String>();
				map.put("title", messagegs.get(i).GetTitle());

				map.put("from", messagegs.get(i).GetFrom());
				map.put("time", messagegs.get(i).GetTime());
				map.put("url", messagegs.get(i).GetUrl());
				maplist.add(map);
			}

			adapter = new SimpleAdapter(InfoListAct.this, maplist,
					R.layout.listadapter, new String[] { "title", "from",
							"time", "url" }, new int[] { R.id.tv_title,
							R.id.tv_from, R.id.tv_time });

			list.setAdapter(adapter);

		} else {
			System.out.println("message is downloading  @@");
			dlog = ProgressDialog.show(InfoListAct.this, "Loading.......",
					"please wait......", true, true);
			System.out.println("message is downloading");
			new Thread() {
				public void run() {

					DeleteHtml();
					if (help.findlist(FLAG) != null) {
						System.out.println("the list has been download");
						handler.obtainMessage(0).sendToTarget();

					}

				}

			}.start();

		}

		bt_load_more.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				progressBar.setVisibility(View.VISIBLE);
				bt_load_more.setVisibility(View.GONE);
				loadMore();
				handler.obtainMessage(3).sendToTarget();

			}
		});

		refreshableView.setOnRefreshListener(new PullToRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				System.out.println("@");
				new Thread() {
					public void run() {

						DeleteHtml();
						if (help.findlist(FLAG) != null) {
							System.out.println("^%&");
							handler.obtainMessage(2).sendToTarget();
						}
					}

				}.start();

			}
		}, 0);

		list.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
						&& lastVisibleIndex == adapter.getCount() - 1) {
					// 当滑到底部时自动加载
					progressBar.setVisibility(View.VISIBLE);
					bt_load_more.setVisibility(View.GONE);
					loadMore();

					handler.obtainMessage(3).sendToTarget();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				// 由于添加了华东的头部指示，导致必须减去头和尾
				lastVisibleIndex = firstVisibleItem + visibleItemCount - 2;
				System.out.println("the lastVisible is " + lastVisibleIndex);
				if (totalItemCount == 12 + 1) {

					list.removeFooterView(moreView);
					Toast.makeText(InfoListAct.this, "数据全部加载完成",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				System.out.println("#####");
				Intent intent = new Intent(InfoListAct.this, NewsShow.class);
				intent.putExtra("url", maplist.get(arg2).get("url"));
				startActivity(intent);
			}
		});

	}

	public void loadMore() {
		FLAG++;
		messagegs = new ArrayList<Messageg>();
		messagegs = help.findlist(FLAG);
		if (messagegs != null) {
			for (int i = messagegs.size() - 1; i >= 0; i--) {
				map = new HashMap<String, String>();
				map.put("title", messagegs.get(i).GetTitle());
				map.put("from", messagegs.get(i).GetFrom());
				map.put("time", messagegs.get(i).GetTime());
				map.put("url", messagegs.get(i).GetUrl());
				maplist.add(map);
			}

		} else {
			bt_load_more.setText("已经无更多数据");
			bt_load_more.setClickable(false);
		}
	}

	@Override
	public void onDestroy() {

		super.onDestroy();

	}

	@Override
	public void onStop() {

		super.onStop();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onResume(InfoListAct.this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(InfoListAct.this);
		maplist = new ArrayList<Map<String, String>>();
		messagegs = new ArrayList<Messageg>();
		messagegs = help.findlist(FLAG);

		if (messagegs != null) {
			System.out.println("#");
			for (int i = messagegs.size() - 1; i >= 0; i--) {
				map = new HashMap<String, String>();
				map.put("title", messagegs.get(i).GetTitle());
				map.put("from", messagegs.get(i).GetFrom());
				map.put("time", messagegs.get(i).GetTime());
				map.put("url", messagegs.get(i).GetUrl());
				maplist.add(map);
			}

			adapter = new SimpleAdapter(InfoListAct.this, maplist,
					R.layout.listadapter, new String[] { "title", "from",
							"time", "url" }, new int[] { R.id.tv_title,
							R.id.tv_from, R.id.tv_time });

			list.addFooterView(moreView);

			list.setAdapter(adapter);
		} else {
			System.out.println("resume ");
			dlog = ProgressDialog.show(InfoListAct.this, "Loading.......",
					"please wait......", true, true);
			System.out.println("@");
			new Thread() {
				public void run() {

					DeleteHtml();
					// if (help.findlist() != null) {
					System.out.println("^%&");
					handler.obtainMessage(0).sendToTarget();

					// }
				}

			}.start();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "清除缓存");

		menu.add(0, 5, 5, "退出");

		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {
		case 0:
			help.Delete();
		case 5:
			finish();

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 返回键最小化程序
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	public String Get() {
		String result = null;
		HttpGet get = new HttpGet(
				"http://ssdut.dlut.edu.cn/index.php/News/student.html");
		try {
			HttpResponse responce = new DefaultHttpClient().execute(get);
			result = Until.Change(responce);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;

	}

	public void DeleteHtml() {
		Document doc = Jsoup.parse(Get());
		Elements elment = doc.select("[bgcolor=#EEEEEE]");
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
		for (int i = elment.size() - 1; i >= 0; i--) {
			Element e = elment.get(i);
			Messageg messageg = new Messageg(e.select("td").first()
					.nextElementSibling().text(), e.select("td").first()
					.nextElementSibling().nextElementSibling().text(), e
					.select("td").last().text(), e.select("td").first()
					.nextElementSibling().select("a").attr("href"));
			help.Insert(messageg);

		}

	}

	// ////获得列编数据并展示

	public static class MtReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			String action = intent.getAction();
			if (action.equals("com.message")) {
				maplist = new ArrayList<Map<String, String>>();
				messagegs = new ArrayList<Messageg>();
				messagegs = help.findlist(FLAG);

				if (messagegs != null) {
					System.out.println("#");

					for (int i = messagegs.size() - 1; i > 0; i--) {
						map = new HashMap<String, String>();
						map.put("title", messagegs.get(i).GetTitle());
						map.put("from", messagegs.get(i).GetFrom());
						map.put("time", messagegs.get(i).GetTime());
						map.put("url", messagegs.get(i).GetUrl());
						maplist.add(map);
					}

					adapter = new SimpleAdapter(context, maplist,
							R.layout.listadapter, new String[] { "title",
									"from", "time", "url" }, new int[] {
									R.id.tv_title, R.id.tv_from, R.id.tv_time });

					list.addFooterView(moreView);

					list.setAdapter(adapter);
				}
			}

		}
	}
}
